<?php
namespace Crm\Table;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Where;
use Zend\Db\Sql\Expression;
class CrmUserTable extends AbstractTable
{
    protected $table = 'hycrm_user';
    protected $id = 'user_id';
    
    public function findByAccountPwd($account, $pwd)
    {
        $rowset = $this->select(array(
            'user_account' => $account, 'user_password'=> $pwd
        ));
        $row = $rowset->current();
        return $row;
    }
    
    public function getUserList($query = array())
    {
        $select = new Select(array('u' =>$this->getTable()));
        $select->join(
            array('org' => 'hy_organization'),
            'u.org_id = org.org_id',
            array('org_name') ,
            $select::JOIN_LEFT
        );
        $select->join(
            array('ug' => 'hycrm_user_group'),
            'u.user_group_id = ug.user_group_id',
            array('user_group_name'),
            $select::JOIN_LEFT
        );
        $select->order('u.user_id');
         
        return $this->fetchPaginate($select,$query);
    }
    
    public function getCrmUserById($id)
    {
        if(empty($id)){
            throw new \Exception("id field is invalid!");
        }
        $sql='SELECT * FROM `hycrm_user` WHERE `user_id` = :user_id';
        $statement=$this->getAdapter()->query($sql);
        $results=$statement->execute(array(':user_id'=>$id));
        $row=$results->current();
        return $row;
    }
    
    public function updateItem($id,$data){
        if(empty($id)){
            throw new \Exception("id field is invalid!");
        }
        $item = array(
            'user_name'=>$data['user_name'],
            'user_group_id'=>$data["user_group_id"],
            'org_id'=>empty($data['org_id']) ? new Expression('NULL') : $data['org_id'],
            'user_position'=>$data["user_position"],
            'user_update_time'=>new Expression('NOW()'),
        );
        if(!empty($data['user_password'])){
            $item['user_password'] = $data['user_password'];
        }
        return $this->update($item,array('user_id'=>$id));
    }
    
    public function addItem($data){
    
        $item = array(
            'user_account'=>$data['user_account'],
            'user_name'=>$data['user_name'],
            'user_password'=>$data['user_password'],
            'user_group_id'=>$data["user_group_id"],
            //'org_id'=>$data["org_id"],
            'user_position'=>$data["user_position"],
            'user_status'=>1,
            'user_create_time'=>new Expression('NOW()'),
            'user_update_time'=>new Expression('NOW()'),
        );
        if(!empty($data['org_id'])){
            $item['org_id'] = $data['org_id'];
        }
        $this->insert($item);
        $id = $this->lastInsertValue;
    
    }
    public function deleteUser($id){
        if(empty($id)){
            throw new \Exception("id field is invalid!");
        }
        return $this->delete(array('user_id'=>$id));
    
    }
}